package com.shamar.blog.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;


/**
 * @author zhy
 * @date 2020-1-2
 * @descrption 获得服务器IP
 */
public class IPUtil {
    private static Logger logger = LoggerFactory.getLogger(IPUtil.class);
    public static String firstIp(){
        String ip = "";
        try {
            Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                Enumeration addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress inetAddress = (InetAddress) addresses.nextElement();
                    if (inetAddress != null && inetAddress instanceof Inet4Address && !inetAddress.getHostAddress().equals("127.0.0.1")) {
                        ip = inetAddress.getHostAddress();
                    }
                }
            }
        }catch (Exception e){
            logger.error("getFirstIp Exception", e.getMessage());
        }
        return ip;
    }
}
